<template>
    <div class="page-box">
        <!-- <breadcrumb id="breadcrumb-container" class="breadcrumb-container" /> -->
        <div class="app-container">
            <div class="filter-container">
                <el-form :inline="true" class="demo-form-inline" label-position="left">
                    <el-form-item label="地市名称" label-width="90px">
                        <el-select v-model="search.cityCode" placeholder="请选择" :disabled="disabled" clearable>
                            <el-option :label="item.label" :value="item.label" v-for="item, i in options"
                                :key="i"></el-option>
                        </el-select>
                    </el-form-item>
                    <!-- <el-form-item label="区县名称" label-width="90px">
                        <el-input v-model="search.districtName" placeholder="请输入"></el-input>
                    </el-form-item> -->
                    <el-form-item label="客户分类" label-width="80px">
                        <el-select v-model="search.customerType" placeholder="请选择" clearable>
                            <el-option label="党政" value="党政"></el-option>
                            <el-option label="交通" value="交通"></el-option>
                            <el-option label="教育" value="教育"></el-option>
                            <el-option label="医卫" value="医卫"></el-option>
                            <el-option label="执法" value="执法"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="服务商" label-width="80px">
                        <el-select v-model="search.providerType" placeholder="请选择" clearable>
                            <el-option label="移动" value="移动"></el-option>
                            <el-option label="联通" value="联通"></el-option>
                            <el-option label="电信" value="电信"></el-option>
                            <el-option label="华为" value="华为"></el-option>
                            <el-option label="浪潮" value="浪潮"></el-option>
                            <el-option label="未招标" value="未招标"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="调度次数" label-width="70px">
                        <el-input v-model="search.recordTimes" placeholder="请输入" clearable></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="onSubmit">查询</el-button>
                        <el-button @click="reset">重置</el-button>
                        <!-- <el-button type="primary" @click="down">导出</el-button> -->
                    </el-form-item>
                </el-form>
            </div>
            <el-button type="primary" @click="handleAdd" v-if="haveEdit()">新增</el-button>
            <el-table :key="tableKey" v-loading="listLoading" :data="list" border fit
                style="width: 100%;margin-top: 16px;" :height="height + 'px'">
                <el-table-column label="地市名称" align="center" v-element-table-tooltip>
                    <template slot-scope="{row}">
                        <span>{{ row.cityCode }}</span>
                    </template>
                </el-table-column>
                <!-- <el-table-column label="区县名称" align="center" v-element-table-tooltip>
                    <template slot-scope="{row}">
                        <span>{{ row.districtName }}</span>
                    </template>
                </el-table-column> -->
                <el-table-column label="客户分类" align="center" v-element-table-tooltip>
                    <template slot-scope="{row}">
                        <span>{{ row.customerType }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="单位名称" align="center" v-element-table-tooltip>
                    <template slot-scope="{row}">
                        <span>{{ row.companyName }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="项目名称" align="center" v-element-table-tooltip>
                    <template slot-scope="{row}">
                        <span>{{ row.projectName }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="服务商" align="center" v-element-table-tooltip>
                    <template slot-scope="{row}">
                        <span>{{ row.providerType }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="调度次数" align="center" width="80px">
                    <template slot-scope="{row}">
                        <span>{{ row.recordTimes || 0 }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="140px">
                    <template slot-scope="scope">
                        <el-button @click="goOkr(scope.row)" type="text">调度</el-button>
                        <el-button type="text" @click="handleEdit(scope)" v-if="haveEdit()">编辑</el-button>
                        <el-button type="text" @click="handleDelete(scope)" v-if="haveEdit()">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" :page.sync="pagination.pageNum"
                :limit.sync="pagination.pageSize" @pagination="getPagination" />
        </div>
        <el-dialog :visible.sync="dialogVisible" :title="dialogType === 'edit' ? '编辑' : '新增'" top="25vh"
            :close-on-click-modal="false">
            <el-form :model="role" label-width="80px" label-position="right" :rules="rules" ref="ruleForm">
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="地市名称" prop="cityCode">
                            <el-select v-model="role.cityCode" placeholder="请选择地市名称" :disabled="disabled" filterable>
                                <el-option :label="item.label" :value="item.label" v-for="item, i in options"
                                    :key="i"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="客户分类" prop="customerType">
                            <el-select v-model="role.customerType" placeholder="请选择客户分类">
                                <el-option label="党政" value="党政"></el-option>
                                <el-option label="交通" value="交通"></el-option>
                                <el-option label="教育" value="教育"></el-option>
                                <el-option label="医卫" value="医卫"></el-option>
                                <el-option label="执法" value="执法"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="单位名称" prop="companyName">
                            <el-input v-model="role.companyName" placeholder="请输入单位名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="项目名称" prop="projectName">
                            <el-input v-model="role.projectName" placeholder="请输入项目名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="服务商" prop="providerType">
                            <el-select v-model="role.providerType" placeholder="请选择">
                                <el-option label="移动" value="移动"></el-option>
                                <el-option label="联通" value="联通"></el-option>
                                <el-option label="电信" value="电信"></el-option>
                                <el-option label="华为" value="华为"></el-option>
                                <el-option label="浪潮" value="浪潮"></el-option>
                                <el-option label="未招标" value="未招标"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div style="text-align:right;">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmRole">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { selectCloudCustomerType, addCloudCustomerType, deleteCloudCustomerType, updateCloudCustomerType } from '@/api/api'
import Pagination from '@/components/Pagination'
import Breadcrumb from '@/components/Breadcrumb'
import moment from 'moment'
import store from '@/store'
import qs from 'querystring'
let query;
export default {
    name: 'customerListCloud',
    components: { Breadcrumb, Pagination },
    watch: {
        dialogVisible(val) {
            if (!val) {
                this.role = { cityCode: this.cityName !== '黑龙江省' ? this.cityName : '' }
                this.$refs['ruleForm'].resetFields();
            }
        }
    },
    data() {
        return {
            cityName: localStorage.getItem('cityName').replace('市', ''),
            role: {},
            rules: {
                cityCode: [
                    { required: true, message: '请选择地市名称', trigger: 'change' }
                ],
                customerType: [
                    { required: true, message: '请选择客户分类', trigger: 'change' }
                ],
                companyName: [
                    { required: true, message: '请输入单位名称', trigger: 'change' }
                ],
                projectName: [
                    { required: true, message: '请输入项目名称', trigger: 'change' }
                ],
                providerType: [
                    { required: true, message: '请选择服务商', trigger: 'change' }
                ]
            },
            dialogVisible: false,
            dialogType: 'new',
            cityName: localStorage.getItem('cityName').replace('市', ''),
            disabled: true,
            height: 600,
            tableKey: 0,
            list: null,
            total: 0,
            listLoading: true,
            search: {},
            options: [{
                value: '0',
                label: '省本级'
            }, {
                value: '30182',
                label: '哈尔滨'
            }, {
                value: '30183',
                label: '齐齐哈尔'
            }, {
                value: '30184',
                label: '牡丹江'
            }, {
                value: '30185',
                label: '佳木斯'
            }, {
                value: '30186',
                label: '大庆'
            }, {
                value: '30187',
                label: '伊春'
            }, {
                value: '30188',
                label: '鸡西'
            }, {
                value: '30189',
                label: '鹤岗'
            }, {
                value: '30190',
                label: '双鸭山'
            }, {
                value: '30191',
                label: '‌七台河'
            }, {
                value: '30192',
                label: '绥化'
            }, {
                value: '30193',
                label: '黑河'
            }, {
                value: '30194',
                label: '大兴安岭'
            }],
            pagination: {
                "pageNum": 1,
                "pageSize": 20
            },
        }
    },
    created() {
        this.disabled = this.cityName !== '黑龙江省'
        query = this.$route.query;
        this.search = { cityCode: this.cityName == '黑龙江省' ? '' : this.cityName, ...query };
        this.getList();
        this.height = this.getHeight();
        let that = this;
        window.onresize = function (event) {
            that.height = that.getHeight();
        };
    },
    methods: {
        down() {
            let params = { ...this.search }
            // window.open(`${process.env.NODE_ENV === 'development' ? '/dev-api' : ''}/api/tasks/export?${qs.stringify(params)}`)
        },
        haveEdit() {
            return this.cityName === '黑龙江省' ? true : query.cityCode ? this.cityName === query.cityCode : true
        },
        handleAdd() {
            this.role = { cityCode: this.cityName !== '黑龙江省' ? this.cityName : '' }
            this.dialogType = 'new'
            this.dialogVisible = true
        },
        async handleEdit(scope) {
            await this.getEdit(scope)
        },
        getEdit(scope) {
            this.dialogType = 'edit'
            this.dialogVisible = true
            this.role = { ...scope.row }
        },
        handleDelete({ $index, row }) {
            this.$confirm(`确认删除“${row.companyName}”单位数据?`, '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(async () => {
                    deleteCloudCustomerType(row.id).then(res => {
                        if (res.code === 200) {
                            this.$message({
                                type: 'success',
                                message: '操作成功!'
                            })
                            this.getList();
                        } else {
                            this.$message({
                                type: 'warning',
                                message: res.message
                            })
                            this.getList();
                        }
                    })
                })
                .catch(err => { console.error(err) })
        },
        confirmRole() {
            this.$refs['ruleForm'].validate((valid) => {
                if (valid) {
                    const isEdit = this.dialogType === 'edit'
                    if (isEdit) {
                        updateCloudCustomerType({ ...this.role }).then(res => {
                            this.dialogVisible = false
                            this.getList()
                        })
                    } else {
                        addCloudCustomerType({ ...this.role }).then(res => {
                            this.dialogVisible = false
                            this.getList()
                        })
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        objectSpanMethod({ row, column, rowIndex, columnIndex }, dataList, idx) {
            if (columnIndex <= 2) {
                const _row = this.flitterData(dataList, 'companyName', idx).one[rowIndex]
                const _col = _row > 0 ? 1 : 0
                return {
                    rowspan: _row,
                    colspan: _col,
                }
            }
        },
        flitterData(arr, name, idx) {
            let spanOneArr = []
            let concatOne = 0
            let checknum = 0;
            arr.forEach((item, index) => {
                if (index === 0) {
                    spanOneArr.push(1)
                } else {
                    if (item[name] === arr[index - 1][name]) {
                        //第一列需合并相同内容的判断条件
                        spanOneArr[concatOne] += 1
                        spanOneArr.push(0)
                    } else {
                        checknum += 1;
                        spanOneArr.push(1)
                        concatOne = index
                    }
                }
            })
            return {
                one: spanOneArr,
            }
        },
        goOkr(item) {
            this.$router.push({ name: 'superviseListSend', params: { add: true, content: `${item.cityCode + item.companyName + item.projectName}`, from: 'cloudCustomer', detail: item } })
        },
        getHeight() {
            let winHieght = window.innerHeight;
            return winHieght - 250;
        },
        getPagination(pagination) {
            this.pagination = pagination;
            this.getList();
        },
        goDetail(row) {
            window.top.postMessage(
                JSON.stringify({
                    to: 'portal',
                    action: 'open',
                    pathname: `/iframe/PROJECT_MENU_MY_PROJECT_PROJECTFULLVIEW?uniqueProjectInstId=${row.UniqueProjectInstId}&bupMenuNo=${row.bupMenuNo}&tableRecord=${row.tableRecord}`,
                }),
                '*'
            )
        },
        onSubmit() {
            this.pagination = {
                "pageNum": 1,
                "pageSize": 20
            }
            this.getList();
        },
        reset() {
            this.pagination = {
                "pageNum": 1,
                "pageSize": 20
            }
            this.search = {};
            this.getList();
        },
        getNumW(num) {
            return this.truncateToFixed(num / 10000, 2)
        },
        truncateToFixed(value, decimals) {
            const integerPart = Math.trunc(value); // 获取整数部分
            const decimalPart = value - integerPart; // 获取小数部分
            const factor = Math.pow(10, decimals);
            const truncatedDecimalPart = decimalPart < 0 ? Math.ceil(decimalPart * factor) / factor : Math.floor(decimalPart * factor) / factor; // 根据正负选择向上或向下截断
            return integerPart + truncatedDecimalPart; // 组合整数部分和小数部分
        },
        getList() {
            this.listLoading = true;
            try {
                let param = {
                    ...this.search,
                    page: this.pagination.pageNum,
                    size: this.pagination.pageSize,
                }
                selectCloudCustomerType(param).then(response => {
                    this.list = response.list || []
                    this.total = response.total || 0
                    this.listLoading = false
                }).finally(e => {
                    this.listLoading = false
                })
            } catch (error) {
                console.log('error', error)
                this.listLoading = false
            }
        }
    }
}
</script>
<style lang="scss" scoped>
.app-container {
    padding: 16px 20px 0;
}

.filter-container {
    padding-bottom: 0;

    ::v-deep .el-form-item {
        margin-bottom: 10px;
    }
}

.pagination-container {
    padding: 0;
}

.page-box {
    background: #fff;
}

::v-deep .el-table th {
    color: #000;
}

::v-deep .el-select--medium {
    min-width: 240px;
}

::v-deep .el-form-item--medium .el-form-item__content {
    min-width: 240px;
}

::v-deep .el-date-editor--daterange.el-input__inner {
    width: 240px;
}

::v-deep .el-select {
    width: 100%;
}
</style>